<?php
/**
 * 分销订单模型
 * 用于记录分销相关的订单信息
 */

namespace app\model;

use think\Model;

class DistributionOrderModel extends Model
{
    // 设置表名
    protected $name = 'sh_distribution_order';
    
    // 设置主键
    protected $pk = 'id';
    
    // 自动写入时间戳
    protected $autoWriteTimestamp = true;
    
    /**
     * 获取分销订单列表
     * @param array $filter 筛选条件
     * @param int $page 页码
     * @param int $limit 每页数量
     */
    public static function getDistributionOrders($filter = [], $page = 1, $limit = 15)
    {
        $query = self::alias('do')
            ->join('order o', 'do.order_id = o.id')
            ->join('customer c', 'o.customer_id = c.id')
            ->join('sh_distribution_distributor dd', 'do.distributor_id = dd.customer_id')
            ->join('customer dc', 'dd.customer_id = dc.id')
            ->field('do.*, o.order_no, o.total_amount, o.status as order_status, c.name as customer_name, dc.name as distributor_name');
            
        // 根据分销员ID筛选
        if (!empty($filter['distributor_id'])) {
            $query->where('do.distributor_id', $filter['distributor_id']);
        }
        
        // 根据订单号筛选
        if (!empty($filter['order_no'])) {
            $query->where('o.order_no', 'like', '%' . $filter['order_no'] . '%');
        }
        
        // 根据订单状态筛选
        if (!empty($filter['order_status'])) {
            $query->where('o.status', $filter['order_status']);
        }
        
        // 根据时间范围筛选
        if (!empty($filter['start_time'])) {
            $query->where('do.create_time', '>=', $filter['start_time']);
        }
        
        if (!empty($filter['end_time'])) {
            $query->where('do.create_time', '<=', $filter['end_time']);
        }
        
        $list = $query->page($page, $limit)->order('do.create_time', 'desc')->select();
        $total = $query->count();
        
        return [
            'list' => $list,
            'total' => $total
        ];
    }
    
    /**
     * 添加分销订单记录
     * @param array $data 订单数据
     */
    public static function addDistributionOrder($data)
    {
        return self::create($data);
    }
    
    /**
     * 更新分销订单记录
     * @param int $id 记录ID
     * @param array $data 更新数据
     */
    public static function updateDistributionOrder($id, $data)
    {
        return self::where(['id' => $id])->update($data);
    }
    
    /**
     * 删除分销订单记录
     * @param int $id 记录ID
     */
    public static function deleteDistributionOrder($id)
    {
        return self::where(['id' => $id])->delete();
    }
    
    /**
     * 根据订单ID获取分销订单信息
     * @param int $order_id 订单ID
     */
    public static function getDistributionOrderByOrderId($order_id)
    {
        return self::where(['order_id' => $order_id])->find();
    }
    
    /**
     * 计算订单佣金
     * @param int $order_id 订单ID
     * @param int $customer_id 客户ID
     */
    public static function calculateCommission($order_id, $customer_id)
    {
        // 获取订单信息
        $order = OrderModel::where(['id' => $order_id])->find();
        if (!$order) {
            return false;
        }
        
        // 获取分销设置
        $settings = DistributionModel::getSettings();
        if (empty($settings['enabled'])) {
            return false;
        }
        
        // 获取客户的一级分销员
        $level1_distributor = DistributionRelationModel::getDistributor($customer_id, 1);
        if (!$level1_distributor) {
            return false;
        }
        
        // 计算一级佣金
        $level1_commission = $order['total_amount'] * ($settings['level1_commission'] / 100);
        
        // 创建一级佣金记录
        $commission_data = [
            'customer_id' => $level1_distributor['customer_id'],
            'from_customer_id' => $customer_id,
            'order_id' => $order_id,
            'order_no' => $order['order_no'],
            'order_amount' => $order['total_amount'],
            'commission_amount' => $level1_commission,
            'level' => 1,
            'status' => 0, // 待结算
            'create_time' => date('Y-m-d H:i:s')
        ];
        
        DistributionCommissionModel::addCommissionRecord($commission_data);
        
        // 更新一级分销员的累计佣金和可提现佣金
        DistributionModel::where(['customer_id' => $level1_distributor['customer_id']])->inc('total_commission', $level1_commission)->inc('withdrawable_commission', $level1_commission)->update();
        
        // 如果启用了二级分销，计算二级佣金
        if ($settings['levels'] == 2) {
            $level2_distributor = DistributionRelationModel::getDistributor($level1_distributor['customer_id'], 1);
            if ($level2_distributor) {
                // 计算二级佣金
                $level2_commission = $order['total_amount'] * ($settings['level2_commission'] / 100);
                
                // 创建二级佣金记录
                $commission_data = [
                    'customer_id' => $level2_distributor['customer_id'],
                    'from_customer_id' => $customer_id,
                    'order_id' => $order_id,
                    'order_no' => $order['order_no'],
                    'order_amount' => $order['total_amount'],
                    'commission_amount' => $level2_commission,
                    'level' => 2,
                    'status' => 0, // 待结算
                    'create_time' => date('Y-m-d H:i:s')
                ];
                
                DistributionCommissionModel::addCommissionRecord($commission_data);
                
                // 更新二级分销员的累计佣金和可提现佣金
                DistributionModel::where(['customer_id' => $level2_distributor['customer_id']])->inc('total_commission', $level2_commission)->inc('withdrawable_commission', $level2_commission)->update();
            }
        }
        
        return true;
    }
}